<template>
  <view class="List">
    <cu-form ref="profileForm">

      <view class="form-group">
        <cu-input required name="STUDENTNAME" title="真实姓名" placeholder="请输入真实姓名"/>
      </view>

<!--      <view class="form-group" v-if="enrollData.STUDENT_FLAGNR">-->
<!--        <cu-input disabled name="STUDENT_FLAGNR" title="学生性质" placeholder="暂无信息"/>-->
<!--      </view>-->

      <view class="form-group">
        <cu-input type="number" name="STUDENTNO" title="学号" placeholder="请输入学号"/>
      </view>

      <view class="form-group">
				<cu-picker required name="ZZTYPE_ID" title="证件类型" :options="ZZTypeOpts" @change="onZZChange"/>
			</view>

      <view class="form-group">
        <cu-input :type="SFZNO_TYPE" name="SFZNO" title="证件号" required placeholder="请输入证件号"/>
      </view>

      <view class="form-group">
        <cu-input required name="PHONENO" title="联系电话" placeholder="请输入联系电话"/>
      </view>

      <view class="form-group">
        <cu-input required name="ADDR" title="现住址" placeholder="请输入现住址"/>
      </view>

      <view class="form-group">
        <cu-radio required name="SEX" title="性别" :options="sexOpt"/>
      </view>

      <view class="margin"></view>

      <view class="form-group">
        <cu-input required name="LXR" title="紧急联系人" placeholder="请输入紧急联系人"/>
      </view>

      <view class="form-group">
        <cu-input required type="number" name="LXR_PHONENO" title="紧急联系人电话" placeholder="请输入紧急联系人电话"/>
      </view>

      <view class="margin"></view>

      <view class="form-group">
        <cu-picker required name="ZZMM" title="政治面貌" :options="ZZMMOpts"/>
      </view>

      <view class="form-group">
        <cu-picker required name="WHCD" title="文化程度" :options="WHCDOpts"/>
      </view>

      <view class="margin"></view>

      <view class="form-group">
        <cu-input name="YDW" title="原单位" placeholder="请输入原单位"/>
      </view>

      <view class="form-group">
        <cu-input name="YZW" title="原职位" placeholder="请输入原职位"/>
      </view>

      <view class="margin"></view>

      <view class="form-group">
        <cu-uploader name="PICID" title="个人照片" compress="true"/>
      </view>

      <view class="form-group" v-if="hasEnroll">
        <cu-uploader disabled name="ZKCNSID" title="老年学员入学协议"/>
				<text class="text-blue margin-left"  @tap="toCommitLetter">重新签名</text>
      </view>

      <view v-else>
        <view class="form-group">
          <view class="padding text-sm flex justify-between">
            <text class="text-blue" @tap="toCommitLetter">查看《老年学员入学协议》并签名</text>
            <text class="text-red" v-if="!hasRead">尚未完成</text>
            <text v-else class="text-green"  @tap="toCommitLetter">已完成</text>
          </view>
        </view>

        <view class="form-group bg-white padding" v-if="ZKCNS && hasRead">
          <cu-uploader ref="uploader" disabled name="ZKCNSID" title="老年学员入学协议"/>
        </view>
      </view>

      <view class="margin"></view>

      <view class="form-group">
        <view class="bg-white padding">
          <view class="title">专业班名称：</view>
          <view class="text-sm text-black margin-top-sm">{{ selectedClassesNames }}</view>
          <view class="text-sm text-blue margin-top" @tap="toChoose" v-if="selectedClassesNames">点击此处重新选择</view>
          <view class="text-sm text-blue margin-top" @tap="toChoose" v-else>点击此处选择班级</view>
        </view>
      </view>

      <view class="form-group">
        <view class="text-sm padding">
          <checkbox @tap="setCheck" class='blue round margin-right-xs' style="transform: scale(0.7)"></checkbox>
          已仔细查看
          <text class="text-blue" @tap="toNotes">《报名须知》</text>
        </view>
      </view>

      <view class="padding">
        <button @tap="uploadfile" :disabled="hasCheck == false" class="cu-btn bg-blue block lg round shadow margin-top-lg">{{hasEnroll?'修改':'提交'}}报名表</button>
      </view>
    </cu-form>
  </view>
</template>

<script lang="ts" setup>
import CuInput from '../../components/cu-input/index.vue'
import CuRadio from '../../components/cu-radio/index.vue'
import CuPicker from '../../components/cu-picker/index.vue'
import CuForm from '../../components/cu-form/index.vue'
import CuUploader from '../../components/cu-uploader/index.vue'
import {computed, nextTick, onBeforeUnmount, onMounted, reactive, Ref, ref, toRefs, watchEffect} from "vue";
import {useStore} from "vuex";
import {usePreview} from "../../utils/usePreview";
import {useProfileArgs} from "../profile/useProfileArgs";
import {useZZTypesList} from "../profile/useZZTypesList";
import {FetchKXClassListDAT, UserEnrollListDAT} from "../../types/responseTypes";
import {getUserEnrollList, updateEnrollZZForm} from "../../api/enroll";
import {useUserEnrollList} from "./useUserEnrollList";
import {useLogin} from "../account/useLogin";
import {getUserData} from "../../api/manage";
import {reDeleteImage} from "../../api/moretap"
const {state, dispatch} = useStore()
const profileForm = ref<any>(null)
const {CUSER_ID, USERNO, USERNAME} = toRefs(useStore().state.user.userInfo)
const {previewImage} = usePreview()
const oldZKCNSID = ref<any>("")
const oldPICID = ref<any>("")
const SFZNO_TYPE = ref("text")

const {ZZMMOpts, WHCDOpts, sexOpt} = useProfileArgs([
  {
    CSNAME: '政治面貌',
    key: 'ZZMMOpts'
  },
  {
    CSNAME: '文化程度',
    key: 'WHCDOpts'
  },
  {
    CSNAME: '性别',
    key: 'sexOpt'
  }
]).opts
const {ZZTypeOpts} = useZZTypesList()

const {isFilledData,hasLogIn,ROLE_ID,hasEnroll} = useLogin()
const selectedClasses = ref<FetchKXClassListDAT[]>([])
const selectedClassesNames = computed(() => selectedClasses.value.map(item => item.CLASSNAME).join('、'))

const {initUserEnrollList,enrollList,ZLList} = useUserEnrollList()
const enrollData = ref({}) as Ref<UserEnrollListDAT>
onMounted(async () => {
  if (!isFilledData.value){
    uni.showModal({
      title:'提示',
      content: '尚未完善资料，请前往完善',
      showCancel: false,
      success: ({confirm}) => {
        if (confirm){
          uni.navigateBack()
        }
      }
    })
    return
  }
  if (hasEnroll.value){
    await initUserEnrollList()
    enrollData.value = enrollList.value[0]
    profileForm.value.setFields(['STUDENTNAME', 'STUDENTNO', 'PICID', 'ZKCNSID','ZZTYPE_ID', 'SFZNO', 'SEX', 'ADDR', 'PHONENO', 'LXR', 'LXR_PHONENO', 'ZZMM', 'WHCD', 'YDW', 'YZW','STUDENT_FLAGNR'].map(name => ({
      value: (enrollData.value[name as keyof UserEnrollListDAT] || '') + '',
      name
    })))
    selectedClasses.value = ZLList.value as any
		oldPICID.value = enrollData.value.PICID
		oldZKCNSID.value = enrollData.value.ZKCNSID

    setSFZNOType(enrollData.value.ZZTYPE_ID);
  }else {
    getUserData(CUSER_ID.value).then(res => {
      if (res.ERROR[0].errcode == '0'){
        if (res.DAT.length > 0){
          profileForm.value.setFields(['STUDENTNAME','STUDENTNO','PICID','ZZTYPE_ID','SFZNO','ADDR','PHONENO','LXR','LXR_PHONENO','ZZMM','WHCD','YDW','YZW'].map(name => ({
            value: res.DAT[0][name] || '',
            name
          })))
          oldPICID.value = res.DAT[0]['PICID'];
          setSFZNOType(res.DAT[0]['ZZTYPE_ID']);
        }
      }else {
        uni.showToast({
          title: res.ERROR[0].error,
          icon: 'none',
          mask: true
        })

      }

      profileForm.value.setFields([
        {
          value: res.DAT[0]['SEX'] || sexOpt[0].value,
          name: 'SEX'
        }
      ])
    }).catch(err => {
      uni.showToast({
        title: '获取资料失败',
        icon: 'error',
        mask: true
      })
      // setTimeout(() => {
      //   uni.navigateBack()
      // },500)
    })
  }


  uni.$on('choose', async (classList) => {
    // await initUserEnrollList()
    // ZLList.value = classList
    selectedClasses.value = classList
  })

  uni.$on('finishSign',url => {
    ZKCNS.value = url
  })

  uni.$on('finishSign',(res) => {
    hasRead.value = true
    ZKCNS.value = res
    nextTick(() => {
      profileForm.value?.setFields([
        {
          name: 'ZKCNSID',
          value: res
        }
      ])
    })
  })
})

watchEffect(async () => {
  if (isFilledData.value){
    await initUserEnrollList()
  }
})

function toChoose(){
	// selectedClasses.value,
  uni.navigateTo({
    url: `/pages/enroll/choose?ZL=${encodeURIComponent(JSON.stringify(selectedClasses.value))}`
  })
}
const hasRead = ref<boolean>(false)
const ZKCNS = ref('')
function toCommitLetter() {
  uni.navigateTo({
    url: '/pages/commitment/index'
  })
}

const hasCheck = ref(false)
function setCheck() {
  hasCheck.value = !hasCheck.value
}
function toNotes() {
  uni.navigateTo({
    url: '/pages/enroll/notes'
  })
}


const uploader = ref<any>(null)

onBeforeUnmount(() => {
  uploader.value?.doDelImg()
})
const {commit} = useStore()
const BASE_URL = import.meta.env.VITE_BASE_API
const PICIDFileName = ref("")
const ZKCNSIDFileName = ref("")
const Roveimges = ref([])
function uploadfile(){
	profileForm.value.submit().then(res=>{
		function files(List,index){
			if(List.length){
				uni.uploadFile({
					url: BASE_URL + '/pic_server/upload', //服务器 url
					filePath: List[index].url, // 要上传文件资源的路径
					name: 'file', // 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
					formData:{
						token:uni.getStorageSync("token"),
						CUSER_ID:state.user.userInfo.CUSER_ID,
						FLAG:List[index].type,
						file: List[index].url
					},
					success(res) {
						let tmpData = JSON.parse(res.data)
						if(List.length -1 == index){
							if(List[index].name == "PICIDFileName"){
								PICIDFileName.value = tmpData.DATA.filename
								Roveimges.value.push(List[index].remove)
							}else{
								ZKCNSIDFileName.value = tmpData.DATA.filename
								Roveimges.value.push(List[index].remove)
							}
							onSubmitEnroll()
						}else{
							if(List[index].name == "PICIDFileName"){
								PICIDFileName.value = tmpData.DATA.filename
								Roveimges.value.push(List[index].remove)
							}else{
								ZKCNSIDFileName.value = tmpData.DATA.filename
								Roveimges.value.push(List[index].remove)
							}
							files(List,index+1)
						
						}
						
					},
					fail(err) {
					
					},
					complete() {
						
					}
				})
			}else{
				onSubmitEnroll()
			}
		
		}
		if(res.PICID||res.ZKCNSID){
			let	list = []
			if(res.PICID){
				if(res.PICID.indexOf("ZP") == -1 )
				list.push({
					url:res.PICID,
					name:"PICIDFileName",
					remove:oldPICID.value,
					type:"ZP"
				})
			}
			if(res.ZKCNSID.indexOf("CNS") == -1){
				list.push({
					url:res.ZKCNSID,
					name:"ZKCNSIDFileName",
					remove:oldZKCNSID.value,
					type:"CNS"
				})
			}
			files(list,0)
		}
		
		
	})
}
async function onSubmitEnroll(){
  try {
    // let ZKCNSID = ''
    // if (!hasEnroll.value){
    //   ZKCNSID = await uploader.value.upload('CNS')
    // }else{
    //   ZKCNSID = ZKCNS.value
    // }
    // const ZKCNSID = await uploader.value?.upload('CNS');
    (profileForm.value.submit() as Promise<any>).then(async values => {
      if (!hasRead.value && !hasEnroll.value){
        uni.showToast({
          title: '请先阅读并签署老年学员入学协议',
          icon: 'none',
          mask: true
        })
        return
      }

      if (selectedClasses.value.length === 0){
        uni.showToast({
          title: '请至少选择一个专业班进行报名',
          icon: 'none',
          mask: true
        })

        return
      }

      // if (!ZKCNSID && !hasEnroll.value){
      //   uni.showToast({
      //     title: '请先上传老年学员入学协议',
      //     icon: 'none',
      //     mask: true
      //   })
      //   return
      // }


      try {
        const {STUDENTNAME,STUDENTNO,PICID,ZZTYPE_ID,SFZNO,SEX,ADDR,ZKCNSID,PHONENO,LXR,LXR_PHONENO,ZZMM,WHCD,YDW,YZW} = values
       
        const res = await updateEnrollZZForm({
          STUDENTNAME,STUDENTNO,ZZTYPE_ID,SFZNO,SEX,ADDR,PHONENO,LXR,LXR_PHONENO,ZZMM,WHCD,YDW,YZW,
          STATE: 1,
					PICID:PICIDFileName.value?PICIDFileName.value:oldPICID.value,
          OPERATOR_ID: CUSER_ID.value || '',
          ZKCNSID: ZKCNSIDFileName.value?ZKCNSIDFileName.value:oldZKCNSID.value,
          CUSER_ID: CUSER_ID.value || '',
          USERNAME: USERNAME.value || '',
          USERNO: USERNO.value || '',
          CLASS_IDS: selectedClasses.value.map(item => item.CLASS_ID).join(';'),
          ENROLL_ID: hasEnroll.value ? enrollData.value.ENROLL_ID : '0'
        })

        if (res.ERROR[0].errcode == '0'){
          commit('HAS_ENROLL',true)
          uni.showToast({
            title: '提交成功',
            icon: "success",
            mask: true
          })
					for(let i = 0;i<Roveimges.value.length;i++){
            if(Roveimges.value[i]){
              reDeleteImage({
								picfilename:Roveimges.value[i]
						  })
            }
						
					}
          setTimeout(() => {
            uni.redirectTo({
            	url: '/pages/pay/list'
            })
          },500)
        }else {
          uploader.value?.doDelImg(true);
          uni.showToast({
            title: res.ERROR[0].error,
            icon: "none",
            mask: true
          })
					if(PICIDFileName.value){
						reDeleteImage({
								picfilename:PICIDFileName.value
						})
					}
					if(ZKCNSIDFileName.value){
						reDeleteImage({
								picfilename:ZKCNSIDFileName.value
						})
					}
        }
      }catch (err){
        uploader.value?.doDelImg(true)
        uni.showToast({
          title: '提交失败',
          icon: 'none',
          mask: true
        })
      }


    }).catch(err => {
      uploader.value?.doDelImg()
      uni.showToast({
        title: '请完善相关资料后再提交',
        icon: 'none',
        mask: true
      })
    })
  }catch (err){
    // uploader?.value.doDelImg(true)
    uni.showToast({
      title: '保存失败',
      icon: 'none',
      mask: true
    })
  }
}


function onZZChange(e: any){
  setSFZNOType(e);
}

function setSFZNOType(id: any){
  if(id == '2'){
    //港澳通行证
    SFZNO_TYPE.value = "text";
  }else{
    SFZNO_TYPE.value = "idcard";
  }
}



</script>

<style scoped lang="scss">
.List{
  box-sizing: border-box;
  padding-bottom: constant(safe-area-inset-bottom);  ///兼容 IOS<11.2/
  padding-bottom: env(safe-area-inset-bottom);  ///兼容 IOS>11.2/
  .form-group+.form-group{
    border-top: 1upx solid #eee;
  }
}
</style>
